// coronavirusStatistic.ts
import { Request, Response } from 'express';
// import { intersection } from 'lodash';
import * as fs from 'fs';
import * as http from 'node:http';

const COV19_URL = 'http://interface.sina.cn/news/wap/fymap2020_data.d.json';

/**
 * 加载疫情每日统计数据
 *
 * @return {*}  {Promise<any>}
 */
const loadCovData = async (): Promise<any> => {
  return new Promise((resolve, reject) => {
    http.get(COV19_URL, (res) => {
      const { statusCode } = res;
      const contentType = res.headers['content-type'] || '';

      let error;
      if (statusCode !== 200) {
        error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`);
      } else if (!/^application\/json/.test(contentType)) {
        error = new Error(
          'Invalid content-type.\n' + `Expected application/json but received ${contentType}`,
        );
      }
      if (error) {
        console.error(error.message);
        res.resume();
        reject(error.message);
        return;
      }

      res.setEncoding('utf8');
      let rawData = '';
      res.on('data', (chunk) => {
        rawData += chunk;
      });
      res
        .on('end', () => {
          try {
            const parsedData = JSON.parse(rawData);
            //   console.log(parsedData);
            resolve(parsedData);
            // resolve(rawData);
          } catch (e: any) {
            console.error(e.message);
            reject(e.message);
          }
        })
        .on('error', (e) => {
          console.error(`Got error: ${e.message}`);
          reject(e.message);
        });
    });
  });
};

export default {
  // 支持值为 Object 和 Array
  'GET /api/coronavirusStatistic': async (req: Request, response: Response) => {
    //   res.status(401).send({
    //     data: {
    //       isLogin: false,
    //     },
    //     errorCode: '401',
    //     errorMessage: '请先登录！',
    //     success: false,
    //   });
    //   return;
    console.log('请求参数 mock/role', req.query);
    try {
      const covData = await loadCovData();
      //   console.time('readCov19');
      const covDataListStr = fs.readFileSync('./mock/database/cov19.json', 'utf-8');
      const covDataList: any[] = covDataListStr ? JSON.parse(covDataListStr) : [];
      const sameDateIndex = covDataList.findIndex(
        (item) => item.mtime.slice(0, 10) === covData.data.mtime.slice(0, 10),
      );
      if (sameDateIndex > -1) {
        covDataList.splice(sameDateIndex, 1, covData.data);
      } else {
        covDataList.push(covData.data);
      }
      fs.writeFileSync('./mock/database/cov19.json', JSON.stringify(covDataList));

      response.send({
        success: true,
        data: covDataList,
      });
    } catch (error: any) {
      response.send({
        data: error,
        errorCode: '',
        errorMessage: typeof error === 'string' ? error : error.message || '',
        success: false,
      });
    }
  },
};
